package com.finalist.controller.admin;

import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.finalist.Message;
import com.finalist.Pageable;
import com.finalist.entity.Store;
import com.finalist.service.AreaService;
import com.finalist.service.StoreService;

@Controller("storeController")
@RequestMapping("/admin/store")
public class StoreController extends BaseController {

	@Resource(name = "storeServiceImpl")
	private StoreService storeService;
	@Resource(name = "areaServiceImpl")
	private AreaService areaService;
	
	@RequestMapping("/list")
	public String list(Pageable pageable,ModelMap model) {
		model.addAttribute("page", storeService.findPage(pageable));
		return "/admin/store/list";
	}
	
	/**
	 * 添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(ModelMap model) {
		return "/admin/store/add";
	}
	
	/**
	 * 保存
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(Store store, ModelMap model, Long areaId) {
		store.setArea(areaService.find(areaId));
		store.setFullAddresss(areaService.find(areaId).toString() + store.getAddress());
		store.setModifyDate(new Date());
		store.setCreateDate(new Date());
		storeService.save(store);
		return "redirect:list.jhtml";
	}
	
	/**
	 * 删除
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public @ResponseBody
	Message delete(Long[] ids) {
		storeService.delete(ids);
		return SUCCESS_MESSAGE;
	}
	
	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Long id, ModelMap model, RedirectAttributes redirectAttributes) {
		Store store = storeService.find(id);
		if (store == null) {
			return ERROR_VIEW;
		}
		
		model.addAttribute("store", store);
		return "/admin/store/edit";
	}
	
	/**
	 * 更新
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public String update(Store store, Long id, Long areaId, RedirectAttributes redirectAttributes) {
		store.setArea(areaService.find(areaId));
		if (!isValid(store)) {
			return ERROR_VIEW;
		}
		Store storeOld = storeService.find(id);
		if (storeOld == null) {
			return ERROR_VIEW;
		}
		storeOld.setAddress(store.getAddress());
		storeOld.setArea(store.getArea());
		storeOld.setFullAddresss(areaService.find(areaId).toString() + store.getAddress());
		storeOld.setModifyDate(new Date());
		storeService.update(storeOld);
		addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
		return "redirect:list.jhtml";
	}
}
